import { Decimal } from 'decimal.js'
/**
 * a*b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
export function decimalMul(a, b) {
  return parseFloat((new Decimal(a).mul(new Decimal(b))).toFixed(4))
}

/**
 * a / b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
export function decimalDiv(a, b) {
  return parseFloat((new Decimal(a).div(new Decimal(b))).toFixed(4))
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (!time) return
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}
/**
 * 获取当前环境的地址前缀
 */
export function getEnvPrefix() {
  const env = process.env.NODE_ENV
  console.log(env, 'env')
  let ret = ''
  switch (env) {
    case 'beta':
      ret = 'ystest-h5'
      break
    case 'development':
      ret = 'h5-dev'
      break
    case 'production':
      ret = 'h5'
      break
  }
  return ret
}

/**
 * 传入图片等级 返回图标信息
 * @param {number}
 * @return {string}
 */
export function reviewScoreLevel(scoreLevel) {
  switch (scoreLevel) {
    case 1:
      return 'xin'
    case 2:
      return 'zuanshi'
    case 3:
      return 'huangguan'
    default:
      return 'huangguany'
  }
}

export function exportExcelFile(res) {
  const blob = new Blob([res.data])
  const downloadElement = document.createElement('a')
  const href = window.URL.createObjectURL(blob)
  if (!res) {
    console.warn('没有二进制流文件')
  }
  console.log(res.headers, '111')
  if (res && res.headers['content-disposition']) {
    try {
      const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1])
      downloadElement.href = href
      downloadElement.download = fileName
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement)
      window.URL.revokeObjectURL(href)
    } catch (e) {
      console.log(e, 'error export')
    }
  } else {
    console.warn("maybe need set 'Access-Control-Expose-Headers' at backend")
  }
}

/**
 * 金额元转分
 * @param num 金额。
 * @param precision 精度。默认为12，一般选12就能解决掉大部分0001和0009问题，而且大部分情况下也够用了，如果你需要更精确可以调高。
 * @returns {number}
 */
export function yuanToFen(num, precision = 12) {
  return +parseFloat((num * 100).toPrecision(precision))
}

/**
 * 金额分转元
 * @param num 金额。
 * @param precision 精度。默认为12，一般选12就能解决掉大部分0001和0009问题，而且大部分情况下也够用了，如果你需要更精确可以调高。
 * @returns {number}
 */
export function fenToYuan(price, digit = 2) {
  let ret
  if (!price && price !== 0) {
    return ''
  } else {
    ret = price / 100
  }
  return ret.toFixed(digit)
}

// 禁止背景层滚动
export const ModalHelper = (function(bodyCls) {
  var scrollTop
  return {
    afterOpen: function() {
      scrollTop = document.scrollingElement.scrollTop
      document.body.classList.add(bodyCls)
      document.body.style.top = -scrollTop + 'px'
    },
    beforeClose: function() {
      document.body.classList.remove(bodyCls)
      // scrollTop lost after set position:fixed, restore it back.
      document.scrollingElement.scrollTop = scrollTop
    }
  }
})('modal-open')

/**
 *
 * @param {订单状态} v
 */
export function orderStatusFilter(v) {
  const n = Number(v)
  switch (n) {
    case 0:
      return '待付款'
    case 1:
      return '已支付，待发货'
    case 2:
      return '已发货'
    case 3:
      return '确认收货'
    case 4:
      return '交易关闭'
    case 5:
      return '分期支付审核中'
    case 6:
      return '审核通过待绑卡'
  }
}

/**
 *
 * @param {Number} expireDate 过期时间 单位毫秒
 */
export function formatDay(expireDate) {
  // 获取当前时间
  // var nowTime = Date.now()
  // var nowTime=new Date().getTime();
  // 获取时间差
  var timediff = Math.round(expireDate / 1000)
  // var timediff = Math.round(172800000 / 1000)

  // 获取还剩多少天
  var day = parseInt(timediff / 3600 / 24)
  // 获取还剩多少小时
  var hour = parseInt((timediff / 3600) % 24)
  // 获取还剩多少分钟
  var minute = parseInt((timediff / 60) % 60)
  // 获取还剩多少秒
  var second = timediff % 60
  return `${day}天${hour}时${minute}分${second}秒`
}

export function payMethodFilter(v) {
  switch (v) {
    case 'OUTER_SOURCE':
      return '支付来源非平台自身'
    case 'SINA_PAY':
      return '新浪支付'
    case 'ALI_PAY':
      return '支付宝'
    case 'LANGHUA_PAY':
      return '浪花黑卡支付'
    case 'DUIGONG_PAY':
      return '对公付款'
    case 'FACE_CARD':
      return '颜值卡支付'
    case 'WECHAT_PAY':
      return '微信支付'
  }
}
export function orderSourceFilter(v) {
  const n = v ? v.toString() : ''
  switch (n) {
    case '0' :
      return '未知'
    case '1' :
      return '安卓'
    case '2' :
      return 'ios'
    case '3' :
      return '手机浏览器（h5）'
    case '4' :
      return '微信'
    case '5' :
      return '桌面浏览器'
    case '6' :
      return 'dsp'
    case '7' :
      return '飞租侠'
    case '8' :
      return '微博h5'
    case '9' :
      return '新浪分期APP'
    case '10' :
      return '微博优选'
    case '11' :
      return '乐享时光'
    case '12' :
      return '一直播'
    case '13' :
      return '新浪闪付'
    case '14' :
      return '无他相机'
    case '77' :
      return '支付宝小程序'
  }
}
export function filterCascaderData(data) {
  if (!data) return false
  const arr = []
  data.forEach(item => {
    if (item.seriesList && item.seriesList.length > 0) {
      item.seriesList.forEach(item1 => {
        if (item1.child && item1.child.length > 0) {
          arr.push(item)
        }
      })
    }
  })
  arr.forEach(item => {
    item.value = item.id
    item.label = item.brandName
    item.children = item.seriesList
    item.children.forEach(item1 => {
      item1.value = item1.seriesId
      item1.label = item1.name
      item1.children = item1.child
      item1.children.forEach(item2 => {
        item2.value = item2.childId
        item2.label = item2.childName
      })
    })
  })
  return arr
}

/**
 * 数字转金额格式
 * @param {String} strNum 待转换数字字符串
 * @param {nNUmber} floatNum 保留几位小数点
 */
export function formatNum(strNum, floatNum = 0) {
  const regex = /[0-9]+?(?=(?:([0-9]{3}))+$)/g
  strNum = strNum + ''
  if (strNum.indexOf('.') === -1) {
    const flaot_str = 1.0.toFixed(floatNum).substr(1)
    strNum = strNum.replace(regex, function(a) { return a + ',' }) + flaot_str
  } else {
    const str_arr = strNum.split('.')
    const float_num = (+('.' + str_arr[1])).toFixed(floatNum).substr(1)
    strNum = str_arr[0].replace(regex, function(a) { return a + ',' }) + float_num
  }
  return strNum
}

/**
 * 较大数据 转 w结尾    10000 => 1.0w
 */
export function formatNumAddW(num = 0) {
  try {
    if (!(['string', 'number'].includes(typeof num))) return null
    const _num = ~~num
    if (_num < 10000) {
      return _num
    } else {
      const Division_num = _num / 10000
      const Last_num = (Division_num + '').indexOf('.') ? Division_num.toFixed(2) : Division_num + '.0'
      return parseFloat(Last_num).toFixed(2) + 'w'
    }
  } catch (error) {
    console.error(error)
  }
}

export const siteMap = {
  '510100': '成都',
  '310100': '上海',
  '320100': '南京',
  '320500': '苏州',
  '500100': '重庆',
  '201': '成都生活',
  '350100': '福州',
  '130300': '秦皇岛',
  '340200': '芜湖',
  '340500': '马鞍山'
}
